<template>
  <a-tooltip
    v-if="showTooltip"
    :content="countryName"
    v-bind="props.tooltip"
  >
    <i
      class="titan-flag-icon"
      :class="[flagIconClass, calcSize && `titan-flag-icon--${calcSize}`]"
      :style="calcStyle"
    />
  </a-tooltip>
  <i
    v-else
    class="titan-flag-icon"
    :class="[flagIconClass, calcSize && `titan-flag-icon--${calcSize}`]"
    :style="calcStyle"
  />
</template>

<script lang="ts" setup>
  import { computed } from "vue";
  import countryMap from "./country-map";
  import { flagProps } from "@/components/flag/src/flag-types";

  defineOptions({ name: "TitanFlag" });

  const props = defineProps(flagProps);

  const formatCountry = computed(() => {
    return countryMap.find((item: { [s: string]: unknown } | ArrayLike<unknown>) => Object.values(item).includes(props.country));
  });

  const countryName = computed(() => {
    const content = typeof props.tooltip === "object" ? props.tooltip.content : "";
    return content || formatCountry.value?.cname || "未知地区";
  });

  const formatCode = computed(() => {
    return formatCountry.value ? formatCountry.value["alpha-2"] : undefined;
  });

  const calcSize = computed(() => {
    return props.size;
  });

  const flagIconClass = computed(() => {
    return formatCode.value ? `fi fi-${formatCode.value}` : `flag-icon flag-unknown`;
  });

  const formatWidth = computed(() => {
    return props.width;
  });

  const showTooltip = computed(() => {
    return typeof props.tooltip !== "undefined" ? !!props.tooltip : !!props.tooltip;
  });

  const calcStyle = computed(() => {
    const style = {
      width: "",
      fontSize: "",
    };
    if (formatWidth.value) {
      style.width = formatWidth.value;
      style.fontSize = formatWidth.value;
    }
    return style;
  });
</script>

<style scoped lang="less">
  .fi-unknown {
    background-image: url("@/icons/svg/flag-unknown.svg");
  }
</style>
